var createError = require('http-errors');
var express = require('express');
var path = require('path');
var logger = require('morgan');

//初始化waterline【连接数据库等】
var waterline = require('./config/waterline');

//form提交表单，解析body的（必须）
var bodyParser = require('body-parser');

//cookie解析器
var cookieParser = require('cookie-parser');

//session
var session = require('express-session');
var MongoStore = require('connect-mongo')(session); //connect和express的mongodb数据库存储

var app = express();

//视图文件夹
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

//form提交表单，解析body的（必须）
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

//解决跨域
app.all('*', function(req, res, next) {
    res.header('Access-Control-Allow-Credentials', true)
    res.header('Access-Control-Allow-Origin', 'https://172.16.4.1:8080')
    res.header('Access-Control-Allow-Headers', 'X-Requested-With')
    res.header('Access-Control-Allow-Methods', 'POST,GET')
    res.header('X-Powered-By', ' 3.2.1')
    res.header('Content-Type', 'application/json;charset=utf-8')
    next()
});

app.use(logger('dev'));
app.use(cookieParser());

//session存储到mongodb
var mongodb = waterline.config.connections.localMongo;
var url = 'mongodb://' + mongodb.user + ':' + mongodb.password + '@' + mongodb.host + ':' + mongodb.port + '/' + mongodb.database + '?authMechanism=' + mongodb.authMechanism + '&authSource=' + mongodb.authSource;

app.use(session({
    secret: '123456',
    name: 'monitor',
    cookie: {
        maxAge: null
    },
    resave: false,
    saveUninitialized: true,
    store: new MongoStore({ //创建新的mongodb数据库
        // host: mongodb.host, //数据库的地址，本机的话就是127.0.0.1，也可以是网络主机
        // port: mongodb.port, //数据库的端口号
        // db: mongodb.database, //数据库的名称。
        // authMechanism: mongodb.authMechanism,
        // authSource: mongodb.authSource,
        url: url
    })
}));

//静态资源文件夹
app.use(express.static(path.join(__dirname, 'public')));

//分发路由文件
var routes = require("./routes");
routes(app);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};
    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;